package cn.edu.scnu.springbootcinema.service;

import cn.edu.scnu.springbootcinema.entity.Movie;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class ReportService {

    @Resource
    private MovieService movieService;
    public void exportFilmRanking(HttpServletResponse response) {
        //从数据库获取电影播放榜单数据
        List<Movie> movieList = movieService.query().orderByDesc("view_count").list();

        //通过POI将数据写入到Excel中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/电影播放榜单报表模板.xlsx");
        if(in==null)return;
        ServletOutputStream out = null;
        XSSFWorkbook excel = null;
        try {
            excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            for(int i=3;i<30;i++)
            {
                //获取第i行
                XSSFRow row = sheet1.getRow(i);
                Movie movie = movieList.get(i-3);
                //写入单元格
                row.getCell(1).setCellValue(i-2);
                row.getCell(2).setCellValue(movie.getTitle());
                row.getCell(3).setCellValue(movie.getType());
                row.getCell(4).setCellValue(movie.getRegion());
                row.getCell(5).setCellValue(movie.getDirector());
                row.getCell(6).setCellValue(movie.getViewCount());
                row.getCell(7).setCellValue(movie.getRating());
                row.getCell(8).setCellValue(movie.getDuration());
                row.getCell(9).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(movie.getReleaseDate()));
                row.getCell(10).setCellValue(movie.getLanguage());
                row.getCell(11).setCellValue(movie.getScriptwriter());
            }
            //输出到浏览器
            out = response.getOutputStream();
            String fileName = URLEncoder.encode("电影播放榜单报表.xlsx", StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            excel.write(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(out!=null)
                    out.close();
                if(excel!=null)
                    excel.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }







    }
}
